from django.shortcuts import render, redirect
from app01.forms.wiki import WikiModelForm
from django.urls import reverse
from django.http import JsonResponse
from app01 import models

def wiki(request, project_id):
    """
    wiki的首页展示 or 文章详情展示
    :param request:
    :param project_id:
    :return:
    """
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')
    wiki_obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'wiki.html', {'wiki_obj': wiki_obj})

def wiki_add(request, project_id):
    """
    wiki添加
    :param request:
    :param project_id:
    :return:
    """
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, request.POST)
    if form.is_valid():
        if not form.instance.parent:
            form.instance.depth = 1
        else:form.instance.depth = form.instance.parent.depth + 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('app01:wiki', kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'wiki_form.html', {'form': form})

def wiki_catalog(request, project_id):
    """
    wiki目录
    :param request:
    :param project_id:
    :return:
    """
    data = models.Wiki.objects.filter(project=request.tracer.project).values('id', 'title', 'parent_id').order_by('depth', 'id')
    return JsonResponse({'status': True, 'data': list(data)})

def wiki_delete(request, project_id, wiki_id):
    """
    删除wiki文章
    :param request:
    :param project_id:
    :param wiki_id:
    :return:
    """
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    return render(request, 'wiki.html')

def wiki_edit(request, project_id, wiki_id):
    """
    编辑wiki文章
    :param request:
    :param project_id:
    :param wiki_id:
    :return:
    """
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_obj:
        return render(request, 'wiki.html')
    if request.method == 'GET':
        form = WikiModelForm(request)
        form.fields['title'] = wiki_obj.title
        form.fields['content'] = wiki_obj.content
        # form.fields['parent'] = wiki_obj.parent
        print(form.instance)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, request.POST)
    if form.is_valid():
        if not form.instance.parent:
            form.instance.depth = 1
        else:
            form.instance.depth = form.instance.parent.depth + 1
        form.save()
        url = reverse('app01:wiki', kwargs={'project_id': project_id})
        current_page = '%s?wiki_id=%s' % (url, wiki_id)
        return redirect(current_page)
    return render(request, 'wiki_form.html', {'form': form})